package com.github.xaidanwang.mybatisshardingjdbc.demo.config;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Collection;

/**
 * @author wang yi fei
 * @date 2020/6/17 10:40
 */
public class TimeShardingTableAlgorithm implements PreciseShardingAlgorithm<String> {
	private static DateTimeFormatter dateformat2 = DateTimeFormatter.ofPattern("yyyyMM");
	private static DateTimeFormatter dateformat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
	private static ZoneId zoneId = ZoneId.systemDefault();
	@Override
	public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<String> shardingValue) {
		StringBuffer tableName = new StringBuffer();
		LocalDateTime createTime = LocalDateTime.parse(shardingValue.getValue(),dateformat);
		LocalDate start = createTime.atZone(zoneId).toLocalDate();
		tableName.append(shardingValue.getLogicTableName())
				.append("_").append(start.format(dateformat2));
		return tableName.toString();
	}
}
